/**
 * 情感趋势图表组件
 * 
 * 作用：展示一段时间内的情感变化趋势
 * 使用：在首页分析区域展示情感变化曲线
 * 数据：接收包含date(日期)、positive(正面)、negative(负面)、neutral(中性)属性的数组
 * 特点：使用折线图展示三种情感的变化趋势，支持时间段切换
 */

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

// 定义属性
const props = defineProps<{
  data: Array<{
    date: string,
    positive: number,
    negative: number,
    neutral: number
  }>
}>()

// 图表实例
let chart: echarts.ECharts | null = null
const chartContainer = ref<HTMLElement | null>(null)

// 时间范围选择
const timeRange = ref('7d')

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) {
    console.error('找不到图表容器元素')
    return
  }
  
  try {
    // 创建图表实例
    chart = echarts.init(chartContainer.value)
    console.log('图表实例创建成功', chart)
    
    // 更新图表数据
    updateChart()
    
    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', handleResize)
  } catch (error) {
    console.error('图表初始化失败:', error)
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

// 更新图表数据
const updateChart = () => {
  if (!chart) {
    console.error('图表实例不存在')
    return
  }
  
  console.log('更新情感趋势图表，原始数据:', props.data)
  
  // 检查数据是否为空
  const hasValidData = props.data && props.data.length > 0 && (
    props.data.some(item => item.positive > 0) || 
    props.data.some(item => item.negative > 0) || 
    props.data.some(item => item.neutral > 0)
  )
  
  // 如果没有数据，显示空状态
  if (!hasValidData) {
    console.warn('情感趋势图表没有有效数据')
    chart.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      series: []
    })
    return
  }
  
  // 清除可能存在的"暂无数据"标题
  chart.setOption({
    title: {
      text: ''
    }
  })
  
  // 根据时间范围筛选数据
  const filteredData = filterDataByTimeRange(props.data, timeRange.value)
  console.log('过滤后的数据:', filteredData)
  
  // 准备数据
  const dates = filteredData.map(item => item.date)
  const positiveData = filteredData.map(item => item.positive)
  const negativeData = filteredData.map(item => item.negative)
  const neutralData = filteredData.map(item => item.neutral)
  
  // 计算Y轴最大值，确保有足够空间
  const maxValue = Math.max(
    ...positiveData,
    ...negativeData,
    ...neutralData
  )
  // 确保Y轴最大值大于0，避免空图表
  const yAxisMax = Math.max(1, Math.ceil(maxValue * 1.2)) // 增加20%的空间
  
  // 改进的颜色方案
  const colors = {
    positive: {
      line: '#36c25b',
      area: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(54, 194, 91, 0.5)' },
        { offset: 1, color: 'rgba(54, 194, 91, 0.05)' }
      ]),
      shadow: 'rgba(54, 194, 91, 0.3)',
      highlight: 'rgba(54, 194, 91, 0.8)'
    },
    negative: {
      line: '#e74c3c',
      area: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(231, 76, 60, 0.5)' },
        { offset: 1, color: 'rgba(231, 76, 60, 0.05)' }
      ]),
      shadow: 'rgba(231, 76, 60, 0.3)',
      highlight: 'rgba(231, 76, 60, 0.8)'
    },
    neutral: {
      line: '#3498db',
      area: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: 'rgba(52, 152, 219, 0.5)' },
        { offset: 1, color: 'rgba(52, 152, 219, 0.05)' }
      ]),
      shadow: 'rgba(52, 152, 219, 0.3)',
      highlight: 'rgba(52, 152, 219, 0.8)'
    }
  }
  
  const option = {
    color: [colors.positive.line, colors.negative.line, colors.neutral.line],
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.98)',
      borderColor: '#f0f0f0',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      padding: [10, 15],
      extraCssText: 'box-shadow: 0 3px 14px rgba(0,0,0,0.15); border-radius: 8px;',
      formatter: function(params: any) {
        let result = `<div style="font-weight: bold; margin-bottom: 8px; font-size: 14px;">${params[0].axisValue}</div>`
        
        params.forEach((item: any) => {
          const color = item.color
          const marker = `<span style="display:inline-block;margin-right:8px;border-radius:50%;width:10px;height:10px;background-color:${color};"></span>`
          let value = item.value
          if (value >= 1000) {
            value = (value / 1000).toFixed(1) + 'k'
          }
          result += `${marker} ${item.seriesName}: <span style="font-weight:bold;float:right;margin-left:20px;">${value}</span><br/>`
        })
        
        return result
      },
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.15)',
          width: 1,
          type: 'dashed'
        }
      }
    },
    legend: {
      data: ['正面情感', '负面情感', '中性情感'],
      icon: 'roundRect',
      itemWidth: 12,
      itemHeight: 6,
      itemGap: 20,
      textStyle: {
        fontSize: 13,
        color: '#666'
      },
      right: '2%',
      top: '0%',
      selected: {
        '正面情感': true,
        '负面情感': true,
        '中性情感': true
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        interval: Math.max(1, Math.floor(dates.length / 8)),
        rotate: 30,
        fontSize: 11,
        color: '#666',
        margin: 16,
        hideOverlap: true,
        formatter: function(value: string) {
          // 简化时间格式显示
          if (value.includes(' ')) {
            // 如果包含空格（日期+时间），只显示时间部分
            return value.split(' ')[1];
          } else if (value.includes(':')) {
            // 如果只有时间格式，直接返回
            return value;
          }
          // 如果是日期格式，显示月/日
          const date = new Date(value);
          if (!isNaN(date.getTime())) {
            return `${date.getMonth() + 1}/${date.getDate()}`;
          }
          return value;
        }
      },
      axisLine: {
        lineStyle: {
          color: '#eaeaea'
        }
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      max: yAxisMax,
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#f0f0f0'
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#666',
        fontSize: 12,
        formatter: function(value: number) {
          if (value >= 1000) {
            return (value / 1000) + 'k'
          }
          return value
        }
      }
    },
    series: [
      {
        name: '正面情感',
        type: 'line',
        data: positiveData,
        symbol: 'emptyCircle',
        symbolSize: 6,
        sampling: 'average',
        itemStyle: {
          color: colors.positive.line,
          borderColor: '#fff',
          borderWidth: 2
        },
        lineStyle: {
          width: 3,
          shadowColor: colors.positive.shadow,
          shadowBlur: 12
        },
        areaStyle: {
          color: colors.positive.area
        },
        smooth: true,
        emphasis: {
          focus: 'series',
          itemStyle: {
            shadowBlur: 10,
            shadowColor: colors.positive.highlight
          }
        }
      },
      {
        name: '负面情感',
        type: 'line',
        data: negativeData,
        symbol: 'emptyCircle',
        symbolSize: 6,
        sampling: 'average',
        itemStyle: {
          color: colors.negative.line,
          borderColor: '#fff',
          borderWidth: 2
        },
        lineStyle: {
          width: 3,
          shadowColor: colors.negative.shadow,
          shadowBlur: 12
        },
        areaStyle: {
          color: colors.negative.area
        },
        smooth: true,
        emphasis: {
          focus: 'series',
          itemStyle: {
            shadowBlur: 10,
            shadowColor: colors.negative.highlight
          }
        }
      },
      {
        name: '中性情感',
        type: 'line',
        data: neutralData,
        symbol: 'emptyCircle',
        symbolSize: 6,
        sampling: 'average',
        itemStyle: {
          color: colors.neutral.line,
          borderColor: '#fff',
          borderWidth: 2
        },
        lineStyle: {
          width: 3,
          shadowColor: colors.neutral.shadow,
          shadowBlur: 12
        },
        areaStyle: {
          color: colors.neutral.area
        },
        smooth: true,
        emphasis: {
          focus: 'series',
          itemStyle: {
            shadowBlur: 10,
            shadowColor: colors.neutral.highlight
          }
        }
      }
    ]
  }
  
  try {
    chart.setOption(option)
    console.log('图表设置选项成功')
  } catch (error) {
    console.error('图表设置选项失败:', error)
  }
}

// 根据时间范围筛选数据
const filterDataByTimeRange = (data: any[], range: string) => {
  if (!data || data.length === 0) return []
  
  // 对于小时数据，不需要过滤，直接返回所有数据
  if (data[0].date.includes(':')) {
    return [...data]
  }
  
  const today = new Date()
  let daysAgo = 0
  
  switch(range) {
    case '7d':
      daysAgo = 7
      break
    case '14d':
      daysAgo = 14
      break
    case '30d':
      daysAgo = 30
      break
    default:
      daysAgo = 7
  }
  
  const startDate = new Date(today)
  startDate.setDate(today.getDate() - daysAgo)
  
  return data.filter(item => {
    const itemDate = new Date(item.date)
    return itemDate >= startDate
  }).sort((a, b) => {
    return new Date(a.date).getTime() - new Date(b.date).getTime()
  })
}

// 更改时间范围
const changeTimeRange = (range: string) => {
  timeRange.value = range
  updateChart()
}

// 监听数据变化，更新图表
watch(() => props.data, (newData) => {
  console.log('数据变化, 新数据:', newData)
  updateChart()
}, { deep: true })

// 组件挂载时初始化图表
onMounted(() => {
  console.log('组件挂载, 初始化图表')
  initChart()
})

// 组件卸载时销毁图表
onBeforeUnmount(() => {
  console.log('组件卸载, 销毁图表')
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="trend-chart-wrapper">
    <!-- 标题和时间范围选择 -->
    <div class="chart-header">
      <h3 class="chart-title">情感变化趋势</h3>
      <div class="time-range-selector">
        <el-radio-group v-model="timeRange" size="small" @change="changeTimeRange">
          <el-radio-button label="7d">7天</el-radio-button>
          <el-radio-button label="14d">14天</el-radio-button>
          <el-radio-button label="30d">30天</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    
    <!-- 图表容器 -->
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<style scoped>
.trend-chart-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 16px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.chart-container {
  width: 100%;
  height: 280px;
}

.time-range-selector :deep(.el-radio-button__inner) {
  border-color: #e0e0e0;
  color: #606266;
  padding: 6px 12px;
  height: auto;
  line-height: 1.5;
}

.time-range-selector :deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #409EFF;
  border-color: #409EFF;
  box-shadow: -1px 0 0 0 #409EFF;
  color: #fff;
}
</style> 